package com.stock.demo.function.home.view;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.AttributeSet;
import android.widget.EditText;

import com.stock.demo.util.SpanResource;

/**
 * Created by XuZhaoyu on 2017/7/31.
 */

public class ChatEditText extends EditText {
    public ChatEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.init();
    }

    public ChatEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.init();
    }

    public ChatEditText(Context context) {
        super(context);
        this.init();
    }

    public void insertAvatar(String avatar, int resId) {
        this.getText().insert(this.getSelectionStart(), SpanResource.convetToSpan(avatar.toString(), this.getContext()));
    }

    private void init() {
        this.setFilters(new InputFilter[]{new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                int[] nAvatarCountOld = SpanResource.getAvatarCount(dest.toString());
                int totalCountOld = dest.toString().length() - nAvatarCountOld[1] + nAvatarCountOld[0];
                int[] nAvatarCountNew = SpanResource.getAvatarCount(source.toString());
                int totalCountNew = source.toString().length() - nAvatarCountNew[1] + nAvatarCountNew[0];
                int totalAvatarCount = nAvatarCountOld[0] + nAvatarCountNew[0];
                int totalCount = totalCountOld + totalCountNew;
                return (CharSequence)(totalAvatarCount <= 20 && totalCount <= 512?source:"");
            }
        }});
    }

    public String getChatText() {
        String text = this.getText().toString();
        return "".equals(text)?"":SpanResource.convertToSendText(text);
    }

    public String getRichText() {
        String text = this.getText().toString();
        return "".equals(text)?"":SpanResource.convertToSendRichText(text);
    }
}
